package com.jingbit.ai.helper;

import android.annotation.SuppressLint;
import android.util.JsonReader;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

@SuppressLint("NewApi")
public class GJsonHelper {

	public static String toJson(Object t){
		Gson gson=new Gson();
		return gson.toJson(t);
	}

	//解析简单Json数据
	public static <T> T parseJson(String jsonData,Class<T> entityType){
		Gson gson=new Gson();
		T t=gson.fromJson(jsonData,entityType);
		return t;
	}

	//解析JsonArray数据
	public static <T> List<T> parseJsonArray(String jsonArrayData, Type type){
		Gson gson = new Gson();
		List<T> list=gson.fromJson(jsonArrayData,type);
		return list;
	}

	/**
	 * @param json
	 * @param clazz
	 * @return
	 */
	public static <T> ArrayList<T> jsonToArrayList(String json, Class<T> clazz)
	{
		Type type = new TypeToken<ArrayList<JsonObject>>()
		{}.getType();
		ArrayList<JsonObject> jsonObjects = new Gson().fromJson(json, type);

		ArrayList<T> arrayList = new ArrayList<>();
		for (JsonObject jsonObject : jsonObjects)
		{
			arrayList.add(new Gson().fromJson(jsonObject, clazz));
		}
		return arrayList;
	}

	//下面两种方法是解析JsonArray的自己写的方法，可用new TypeToken<List<T>>(){}.getType()代替

	public static <T> List<T> readJsonArray(JSONArray array, Class<T> entityType) {
		Gson gson = new Gson();
		List<T> list = new ArrayList<T>();
		for (int i = 0; i < array.length(); i++) {
			try {
				T t = gson.fromJson(array.getJSONObject(i).toString(), entityType);
				list.add(t);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return list;
	}

	public static <T> List<T> readJsonArray(String array, Class<T> entityType) throws JSONException {
		Gson gson = new Gson();
		JSONArray jsonArray=new JSONArray(array);
		List<T> list = new ArrayList<T>();
		for (int i = 0; i < array.length(); i++) {
			try {
				T t = gson.fromJson(jsonArray.getJSONObject(i).toString(), entityType);
				list.add(t);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return list;
	}

	public static String remakeJson(String json) {
		json = json.replace("{", "").replace("}", "");
		StringBuffer buffer = new StringBuffer("{");
		String[] jsons = json.split(",");
		for (int vari = 0; vari < jsons.length; vari++) {
			String str = jsons[vari];
			str = str.replace("=", "\":\"");
			if (vari + 1 != jsons.length) {
				buffer.append("\"" + str + "\",");
			} else {
				buffer.append("\"" + str + "\"");
			}
		}
		buffer.append("}");
		return buffer.toString();
	}
	
}
